//package ynu.lcy.elememicroservicegateway.filter;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//import ynu.lcy.elememicroservicecommon.exception.BusinessException;
//import ynu.lcy.elememicroservicecommon.utils.ErrorCode;
//import ynu.lcy.elememicroservicegateway.service.NonceService;
//import ynu.lcy.elememicroservicegateway.utils.CommonUtils;
//
//import java.time.Instant;
//import java.util.List;
//
//@Component
//public class GlobalTimeStampNonceFilter implements GlobalFilter, Ordered {
//
//    @Autowired
//    private NonceService nonceService;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest serverHttpRequest = exchange.getRequest();
//        String nonce = serverHttpRequest.getHeaders().getFirst("X-Nonce");
//        String timestamp =  serverHttpRequest.getHeaders().getFirst("X-Timestamp");
//        if (nonce == null || timestamp == null) {
//            return CommonUtils.buildErrorResponse(exchange.getResponse(),
//                    HttpStatus.FORBIDDEN, ErrorCode.FORBIDDEN_ERROR);
//        }
//
//        long requestTime = Long.parseLong(timestamp);
//        long currentTime = Instant.now().toEpochMilli();
//
//        // 允许两分钟误差
//        if (Math.abs(currentTime - requestTime) > 2 * 60 * 1000) {
//            return CommonUtils.buildErrorResponse(exchange.getResponse(),
//                    HttpStatus.FORBIDDEN, ErrorCode.TIMESTAMP_EXPIRE_ERROR);
//        }
//
//        if (nonceService.isNonceUsed(nonce)) {
//            return CommonUtils.buildErrorResponse(exchange.getResponse(),
//                    HttpStatus.FORBIDDEN, ErrorCode.NONCE_USED_ERROR);
//        }
//        //标记
//        nonceService.markNonceAsUsed(nonce);
//        return chain.filter(exchange);
//
//    }
//    /**
//     * 优先级提到最高
//     * @return
//     */
//    @Override
//    public int getOrder() {
//        return 0;
//    }
//}
